﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using Cartoon.Model;
using Cartoon.Common;
using Belyn.Common.Web;
using Cartoon.Logic;
using Cartoon.Skin;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Threading;

namespace CartoonViewer
{
    public class ChapterListPanel : ListPanel, IChapterList, ICartoonView
    {
        private Thread _threadLoadChapter;
        private Thread threadLoadChapter
        {
            get
            {
                if (_threadLoadChapter == null || !_threadLoadChapter.IsAlive)
                {
                    _threadLoadChapter = new Thread(new ThreadStart(startLoadChapterList));
                    _threadLoadChapter.IsBackground = true;
                    _threadLoadChapter.Priority = ThreadPriority.BelowNormal; 
                }

                return _threadLoadChapter;
            }

            set
            {
                this._threadLoadChapter = value;
            }
        }
        public ChapterListPanel()
            : base()
        {
            IsLoadingChapter = false;

            //taskFactory = new TaskFactory();
            //taskFactory
            //this.BGWorkerLoadChapter = new BackgroundWorker();
            //this.BGWorkerLoadChapter.DoWork += new DoWorkEventHandler(BGWorkerLoadChapter_DoWork);
            //this.BGWorkerLoadChapter.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BGWorkerLoadChapter_RunWorkerCompleted);

            //this.BGWorkerLoadChapter.WorkerSupportsCancellation = true;
        }

        private List<UC_Chapter>  _chapterList;
        protected List<UC_Chapter> ChpList
        {
            get
            {
                if (this._chapterList == null)
                {
                    this._chapterList = new List<UC_Chapter>();
                }
                return this._chapterList;
            }
            set
            {
                this._chapterList = value;
            }
        }
         

        private IDownload GetDownloading(Chapter chp)
        {
            string downloadTitle = chp.comic.Name + "第" + chp.Id + "话";

            IDownload d = this.CartoonDownLoadMgr.Get(downloadTitle);

            return d;
        }

        private void uc_Chp_Download(object sender, Chapter chp)
        {
            CartoonDownload cartoonDL = new CartoonDownload(chp, this);
            this.CartoonDownLoadMgr.Add(cartoonDL);

            UC_Chapter ucChapter = sender as UC_Chapter;
            if (ucChapter != null)
            {
                ucChapter.Downloader = cartoonDL;
            }

            cartoonDL.Download();
        }

        #region IChapterList 成员

        public ISkinService Skin { get; set; }

        public CartoonDownloadManage CartoonDownLoadMgr
        {
            get;
            set;
        }
        public Comic CurrentComic 
        { 
            get; set; 
        }

        public List<UC_Chapter> GetChapterList()
        {
            return this.ChpList;
        }

        public bool IsLoadingChapter
        {
            get;
            set;
        }

        protected void AddChapter(UC_Chapter uc_chp)
        {
            if (uc_chp == null || this.ChpList.Contains(uc_chp) == true)
            {
                return;
            }

            this.ChpList.Add(uc_chp);
            this.Children.Add(uc_chp);

            uc_chp.Margin = new Thickness(this.Margin_Left, this.Margin_Top, 0, 0);
            uc_chp.SetValue(Grid.RowProperty, this.RowNum);
            uc_chp.SetValue(Grid.ColumnProperty, this.ColumnNum);

            if (this.RowDefinitions.Count < this.RowNum + 1)
            {
                this.RowDefinitions.Add(new RowDefinition());
            }  
        }

        public int ChapterNum 
        { 
            get 
            { 
                return this.ChpList.Count; 
            } 
        }

        public event Action<IChapterList> EventChapterListLoaded;
        protected void OnChapterListLoaded()
        {
            if (this.EventChapterListLoaded != null)
            {
                this.EventChapterListLoaded(this);
            }
        }

        public void LoadChapterList()
        {
            Log.log("加载漫画《" + this.CurrentComic.Name + "》集数..."); 
            this.threadLoadChapter.Start(); 
        }

        private void startLoadChapterList()
        {
            this.IsLoadingChapter = true;

            ChapterList chpList = null;
            try
            {
                chpList = this.EventGetChapterList(this.CurrentComic);
            }
            catch (Exception ex)
            {
                Log.debug(ex.Message);
                return;
            }

            chpList.Sort(true);
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.Clear();
            }));

            foreach (Chapter chp in chpList)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    UC_Chapter uc_Chp = null;
                    uc_Chp = new UC_Chapter(this, chp);
                    uc_Chp.Download += new DownloadChapterDelegate(uc_Chp_Download);
                    IDownload d = this.GetDownloading(chp);
                    if (d != null)
                    {
                        uc_Chp.Downloader = d;
                    }
                    this.AddChapter(uc_Chp);
                }));
            }

            this.IsLoadingChapter = false;
            //new Task(() => 
            //{ 
            //    foreach (var chp in this.ChpList.ToList())
            //    {
            //        chp.CheckState();
            //    }
            //}).Start();
        }

        public void StopLoadChapterList()
        {
            try
            {
                this.IsLoadingChapter = false; 
            }
            catch (Exception ignore) { }

            try
            {
                this.threadLoadChapter.Abort();
            }
            catch (Exception ignore)
            { }
            finally
            {
                this.threadLoadChapter = null;
            }
        }

        private void BGWorkerLoadChapter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.IsLoadingChapter = false;
        }

        private void BGWorkerLoadChapter_DoWork(object sender, DoWorkEventArgs e)
        {
            this.startLoadChapterList();
        }  

        #endregion

        #region IPanelList 成员

        public override void Clear()
        {
            base.Clear();
            this.ChpList.Clear();
        } 
         

        #endregion

        #region ICartoonView 成员

        public event SaveImageDelegate EventSaveImage;

        public event GetChapterListDelegate EventGetChapterList;

        public string Domain
        {
            get;
            set;
        }

        public string Domain_Pic
        {
            get;
            set;
        }

        public string RootUrl
        {
            get;
            set;
        }

        public string CartoonSavePath
        {
            get;
            set;
        }

        #endregion
    }
}
